package com.ustcinfo.ishare.kafka.monitor.controller;

import com.ustcinfo.ishare.kafka.monitor.bean.KafkaConfigFile;
import com.ustcinfo.ishare.kafka.monitor.service.IKafkaConfigFileService;
import com.ustcinfo.ishare.kafka.monitor.utils.SystemConfigUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * Created by Shinelon on 2018/4/17.
 */
@Controller
@RequestMapping("/fileUploadDownload")
public class FileUploadDownloadController {
    @Autowired
    IKafkaConfigFileService kafkaConfigFileService;

    @RequestMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request, Model model) throws IOException {
        // uploads文件夹位置
        String rootPath = SystemConfigUtils.getProperty("upload.url") + "resource/uploads/";
        // 原始名称
        String originalFileName = file.getOriginalFilename();
        File dateDirs = new File(rootPath);

        // 新文件
        File newFile = new File(rootPath + originalFileName);
        // 判断目标文件所在目录是否存在
        if( !newFile.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }
        // 将内存中的数据写入磁盘
        file.transferTo(newFile);

        KafkaConfigFile kafkaConfigFile = new KafkaConfigFile();
        kafkaConfigFile.setConfigFileName(originalFileName);
        kafkaConfigFile.setConfigFileUrl(rootPath + originalFileName);
        kafkaConfigFile.setCreateTime(new Date().getTime());
        kafkaConfigFileService.insert(kafkaConfigFile);

        List<KafkaConfigFile> kafkaConfigFileList = kafkaConfigFileService.findAllKafkaConfigFile();
        model.addAttribute("kafkaConfigFileList",kafkaConfigFileList);

        return "configFileManager";
    }

    @RequestMapping("/download")
    public void download(HttpServletRequest request,HttpServletResponse response) throws Exception{
        int id = Integer.valueOf(request.getParameter("id"));

        KafkaConfigFile kafkaConfigFile = kafkaConfigFileService.getKafkaConfigFileById(id);
        String url = kafkaConfigFile.getConfigFileUrl();
        String name = kafkaConfigFile.getConfigFileName();
        File file = new File(url);

        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="+new String(name.getBytes("UTF-8"),"iso-8859-1"));

        InputStream inputStream = new FileInputStream(file);
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        os.close();
        inputStream.close();
    }

    @RequestMapping("/seeFile")
    @ResponseBody
    public String seeFile(HttpServletRequest request){
        int id = Integer.valueOf(request.getParameter("id"));

        KafkaConfigFile kafkaConfigFile = kafkaConfigFileService.getKafkaConfigFileById(id);
        String url = kafkaConfigFile.getConfigFileUrl();
        File file = new File(url);

        String encoding = "UTF-8";
        Long fileLength = file.length();
        byte[] fileContent = new byte[fileLength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(fileContent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(fileContent, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }
}
